package org.abacus.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;

public class StringHttpRequest extends HttpRequest<String, String> {

	public StringHttpRequest(String url) throws HttpException {
		super(url);
	}

	public Response<String> doWork(String arg0) throws HttpException {
		try {
			conn.setRequestMethod(getRequestMethod());
			conn.setRequestProperty("Content-Type", getContentType());
			conn.setRequestProperty("Content-Length", getContentLength());
			conn.setRequestProperty("Cookie", ";" + getCookie());
			if (null != arg0) {
				setContentLength(String.valueOf(arg0.length()));
				conn.setRequestProperty("Content-Length", getContentLength());
				conn.setDoOutput(true);
				OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), getCharsetEncoding());
				osw.write(arg0);
				osw.flush();
			}
			setCookie(conn.getHeaderField("Set-Cookie"));
		} catch (IOException e) {
			throw new HttpException(e.getMessage(), e, "IOException");
		}
		InputStream is = null;
		try {
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				is = conn.getInputStream();
			} else {
				is = conn.getErrorStream();
			}
		} catch (IOException e) {
			throw new HttpException(e.getMessage(), e, "IOException");
		}
		StringHttpResponse response = new StringHttpResponse(is);
		response.setCharsetEncoding(getCharsetEncoding());
		return response;
	}
}
